<template>
    <div class="ocr">
        <FormTopDesc :desc="'প্রোটোকল'" :info="'প্রমাণীকরণের জন্য আইডি কার্ড + ট্যাক্স কার্ড'"></FormTopDesc>
        <div class="ocr-upload">
            <div class="ocr-top">
                <!-- 身份证前 -->

                <div class="ocr-sfqian">
                    <div class="ocr-sfqian-img" @click="dosfzqian">
                        <input class="sfz" id="sfzqian" type="file" accept="image/*" capture="camera"
                            @change="handleFileInput">
                        <img ref="photo" :src="sfqian" alt="">
                    </div>
                    <div class="ocr-sfqian-desc">আইডি কার্ড সামনে</div>
                </div>
                <!-- 身份证后 -->
                <div class="ocr-sfhou">
                    <div class="ocr-sfhou-img" @click="dosfzhou">
                        <input class="sfz" id="sfzhou" type="file" accept="image/*" capture="camera"
                            @change="handleFileInputsfhou">
                        <img ref="phototwo" :src="sfhou" alt="">
                    </div>
                    <div class="ocr-sfhou-desc">আইডি কার্ডের উল্টো দিকে</div>
                </div>
            </div>
        </div>
        <div class="ocr-err">
            <div class="ocr-err-desc">ত্রুটি মামলা</div>
            <div class="ocr-err-img">
                <ul class="ocr-e">
                    <li>
                        <div class="ocr-errimg">
                            <img src="../../assets/images/err-1.png" alt="">
                        </div>
                        <div class="ocr-err-img-desc">ঝাপসা ছবি</div>
                    </li>
                    <li>
                        <div class="ocr-errimg">
                            <img src="../../assets/images/err-2.png" alt="">
                        </div>
                        <div class="ocr-err-img-desc">অসম্পূর্ণ ছবি</div>
                    </li>
                    <li>
                        <div class="ocr-errimg">
                            <img src="../../assets/images/err-3.png" alt="">
                        </div>
                        <div class="ocr-err-img-desc">ছবি অবরুদ্ধ</div>
                    </li>
                </ul>
            </div>
        </div>
        <button class="ocr-btn" @click="doSubmit">আবেদন জমা দিন</button>
    </div>
</template>
<script>
import { uploadFileApi, getOCRApi } from "../../api";
import { jiami, jiemi } from "../../utils/AESKey.js";
import { Toast } from "vant";
export default {
    name: 'ocr',
    data() {
        return {
            sfqian: require('../../assets/images/sfqian.png'),
            sfhou: require('../../assets/images/sfhou.png'),
            user: {
                sfqian: '',
                sfhou: '',
            }
        }
    },
    methods: {
        //提交
        async doSubmit() {
            if (!(this.user.sfqian && this.user.sfhou)) {
                Toast('নথি আপলোড করুন')
            } else {
                this.$store.commit('setOCRUrl', this.user)
                const f = {
                    model: {
                        url: '',
                        url1: ''
                    }
                }
                f.model.url = this.user.sfqian
                f.model.url1 = this.user.sfhou
                const res = await getOCRApi(jiami(f))
                this.$store.commit('setocrForm', jiemi(res.data).model)
                console.log(jiemi(res.data), 'ocr结果')
                this.$router.push('/ocrForm')
            }
        },
        //base64转成file对象
        base64toFile(base64String, fileName) {
            const binaryString = atob(base64String.split(',')[1]);
            const buffer = new ArrayBuffer(binaryString.length);
            const bytes = new Uint8Array(buffer);

            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }

            const blob = new Blob([buffer], { type: 'image/png' });
            return new File([blob], fileName, { type: 'image/png' });
        },
        handleFileInput(event) {
            this.$store.commit('showLoading')
            // 获取图片元素的引用
            const photo = this.$refs.photo
            // 获取用户选择的文件对象
            const file = event.target.files[0]
            // 创建一个FileReader对象，用于读取文件内容
            const reader = new FileReader()
            // 当文件读取完成后，触发onload事件
            reader.onload = async () => {
                // 将读取的文件内容设置为图片的src属性
                // photo.src = reader.result
                
                const newFile = this.base64toFile(reader.result, file.name)
                const fileObj = {
                    content: reader.result,
                    file: newFile,
                    message: '',
                    status: ''
                }
                const newFileObj = await this.photoZip(fileObj.file)
                //压缩后的
                const res = await uploadFileApi(newFileObj)
                // console.log(jiemi(res.data), '上传图片的结果身份证前')
                this.sfqian = jiemi(res.data).model.id
                this.user.sfqian = jiemi(res.data).model.id
            }
            // 开始读取文件内容，这会触发onload事件
            reader.readAsDataURL(file)
        },
        handleFileInputsfhou(event) {
            this.$store.commit('showLoading')
            // 获取图片元素的引用
            const photo = this.$refs.phototwo
            // 获取用户选择的文件对象
            const file = event.target.files[0]
            // 创建一个FileReader对象，用于读取文件内容
            const reader = new FileReader()
            // 当文件读取完成后，触发onload事件
            reader.onload = async () => {
                // 将读取的文件内容设置为图片的src属性
                // photo.src = reader.result
                const newFile = this.base64toFile(reader.result, file.name)
                const fileObj = {
                    content: reader.result,
                    file: newFile,
                    message: '',
                    status: ''
                }
                const newFileObj = await this.photoZip(fileObj.file)
                //压缩后的
                const res = await uploadFileApi(newFileObj)
                // console.log(jiemi(res.data), '上传图片的结果身份证前')
                this.user.sfhou = jiemi(res.data).model.id
                this.sfhou = jiemi(res.data).model.id
            }
            // 开始读取文件内容，这会触发onload事件
            reader.readAsDataURL(file)
        },
        //身份证前
        dosfzqian() {
            document.getElementById('sfzqian').click()
        },
        //身份证后
        dosfzhou() {
            document.getElementById('sfzhou').click()
        },
        async photoZip(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => {
                    const base64 = reader.result;
                    const img = new Image();
                    img.src = base64;
                    img.onload = () => {
                        const canvas = document.createElement('canvas');
                        const context = canvas.getContext('2d');
                        canvas.width = img.width;
                        canvas.height = img.height;
                        context.drawImage(img, 0, 0);
                        const quality = 0.7;
                        const maxWidth = 800;
                        const maxHeight = 800;
                        let newBase64 = canvas.toDataURL('image/jpeg', quality);
                        console.log(newBase64.length / 1024, '11111111111111')
                        while (newBase64.length / 1024 > 100) {
                            canvas.width *= 0.9;
                            canvas.height *= 0.9;
                            context.drawImage(img, 0, 0, canvas.width, canvas.height);
                            newBase64 = canvas.toDataURL('image/jpeg', quality);
                        }
                        const blob = this.dataURLtoBlob(newBase64);
                        const newFile = new File([blob], file.name, { type: 'image/jpeg' });
                        console.log(newBase64.length / 1024, '33333333')
                        // 返回file对象格式
                        resolve({ file: newFile, content: newBase64, message: '', status: '' });
                    }
                }
                reader.onerror = reject;
            }
            );
        },
        dataURLtoBlob(dataURL) {
            const arr = dataURL.split(',');
            const mime = arr[0].match(/:(.*?);/)[1];
            const bstr = atob(arr[1]);
            let n = bstr.length;
            const u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        }
    },
}
</script>

<style lang="less" scoped>
.ocr {
    width: 100vw;
    height: (667/@a);
    background-color: #f5f5f5;
    padding-top: (110/@a);

    .ocr-upload {
        width: (330/@a);
        height: (183/@a);
        background: #FFFFFF;
        border-radius: (16/@a);
        margin-top: (12/@a);
        margin-left: (23/@a);

        .sfz {
            display: none;
        }

        .ocr-top {
            width: (330/@a);
            height: (166/@a);
            display: flex;
            padding: (17/@a);
            box-sizing: border-box;

            .ocr-sfqian {
                width: (135/@a);
                height: (103/@a);
                margin-right: (27/@a);

                .ocr-sfqian-img {
                    width: (135/@a);
                    height: (103/@a);
                    background: #ECF0FD;
                    border: (2/@a) solid #415AB8;
                    border-radius: (10/@a);



                    img {
                        width: (130/@a);
                        height: (100/@a);
                    }
                }

                .ocr-sfqian-desc {
                    font-size: (11/@a);
                    font-family: Nirmala UI;
                    font-weight: bold;
                    color: #7F7F7F;
                    margin-top: (12/@a);
                    margin-left: (10/@a);
                }
            }

            .ocr-sfhou {
                width: (135/@a);
                height: (103/@a);

                .ocr-sfhou-img {
                    width: (135/@a);
                    height: (103/@a);
                    background: #ECF0FD;
                    border: (2/@a) solid #415AB8;
                    border-radius: (10/@a);

                    img {
                        width: (130/@a);
                        height: (100/@a);
                    }
                }

                .ocr-sfhou-desc {
                    width: (114/@a);
                    height: (34/@a);
                    font-size: (11/@a);
                    font-family: Nirmala UI;
                    font-weight: bold;
                    color: #7F7F7F;
                    margin-top: (5/@a);
                    margin-left: (20/@a);
                }
            }
        }
    }

    .ocr-err {
        width: (329/@a);
        height: (154/@a);
        background: #FFFFFF;
        border-radius: (10/@a);
        margin-top: (8/@a);
        margin-left: (23/@a);
        padding-top: (12/@a);

        .ocr-err-desc {
            font-size: (13/@a);
            font-family: Nirmala UI;
            font-weight: bold;
            color: #151515;
            margin-left: (121/@a);
        }

        .ocr-err-img {
            .ocr-e {
                width: (329/@a);
                height: (100/@a);
                display: flex;
                justify-content: space-around;
                margin-top: (12/@a);

                .ocr-errimg {
                    width: (86/@a);
                    height: (68/@a);

                    img {
                        width: 100%;
                    }
                }

                .ocr-err-img-desc {
                    font-size: (11/@a);
                    font-family: Nirmala UI;
                    font-weight: bold;
                    margin-top: (12/@a);
                    color: #7F7F7F;
                    margin-left: (5/@a);
                }
            }
        }
    }

    .ocr-btn {
        width: (329/@a);
        height: (53/@a);
        background: #415AB8;
        border-radius: (10/@a);
        margin-top: (8/@a);
        margin-left: (23/@a);
        text-align: center;
        line-height: (53/@a);
        font-size: (16/@a);
        font-family: Nirmala UI;
        font-weight: bold;
        color: #FFFFFF;
    }
}
</style>